/********************************************************************************
 * Copyright (c)2016-2020, ShenZhen WanJiaAn Technology CO.,LTD.
 * All Rights Reserved.
 *
 * File Name     : hal_flash.c
 * Author        : joki.zhu
 * Date          : 2019-10-30
 *
 * Record        :
 * 1.Date        : 2019-10-30
 *   Author      : joki.zhu
 *   Modification: Created file
 ********************************************************************************/
#include "app_common.h"
#include "spinor.h"

extern struct mtd_info* spinor_mtd;



HI_VOID spi_raw_get_info
(
    HI_U64* totalsize,
    HI_U32* pagesize,
    HI_U32* blocksize,
    HI_U32* oobsize,
    HI_U32* blockshift)
{
    *totalsize  = spinor_mtd->size;
    *pagesize   = spinor_mtd->writesize;
    *blocksize  = spinor_mtd->erasesize;
    *oobsize    = spinor_mtd->oobsize;
}

int hal_flash_erase(int fd, unsigned long startaddr, unsigned long length)
{
    int ret = 0;
	struct erase_info   st_erase;

	if ((length <= 0) || (NULL == spinor_mtd->erase)) {
		LOGE( "length is:%d ,spinor_mtd->erase:0x%p\n", length, spinor_mtd->erase);
		return -1;
	}
	
	memset(&st_erase, 0, sizeof(struct erase_info));
	st_erase.mtd             = spinor_mtd;
	st_erase.callback        = NULL;
	st_erase.fail_addr       = -1LL;
	st_erase.addr            = startaddr;
	st_erase.len             = length;
	st_erase.time            = 1;
	st_erase.retries         = 1;
	st_erase.dev             =0;
	st_erase.cell            = 0;
	st_erase.priv            =0;
	st_erase.state           = 0;
	st_erase.next            = NULL;
	st_erase.scrub           = 0;

	ret = spinor_mtd->erase(spinor_mtd, &st_erase);
	if (0 != ret) {
		LOGE( "spiflash_erase_proc erase error,lret[%u]\n", ret);
	}
	
	LOGD("flash_erase ok .startaddr = 0x%x\n",startaddr);
	
	return ret;
}

int hal_flash_write(int fd, void *databuf, unsigned long startaddr, unsigned long length)
{
    int ret = 0;
	unsigned int ul_retlen = 0;

	if ((length <= 0) || (NULL == spinor_mtd->write)) {
		LOGE( "length is:%d ,spinor_mtd->write:0x%p\n", length, spinor_mtd->write);
		return -1;
	}

	ret =  spinor_mtd->write(spinor_mtd, startaddr, length, &ul_retlen, databuf);
	if (0 != ret) {
		LOGE( "spiflash_write_proc write error,lret[%u],ul_retlen[%u]\n", ret, ul_retlen);
	}
	
	LOGD("flash_write ok  startaddr[0x%x] length[0x%x] ul_retlen[0x%x] databuf[0x%x]\n",startaddr,length,ul_retlen,databuf);

	return ret;
}

int hal_flash_read(int fd, void *databuf, unsigned long startaddr, unsigned long length)
{
	int ret = 0;
	unsigned int ul_retlen = 0;

	if ((length <= 0) || (NULL == spinor_mtd->read)) {
		LOGE( "ul_size is:%d ,spinor_mtd->read:0x%p\n", length, spinor_mtd->read);
		return -1;
	}

	ret = spinor_mtd->read(spinor_mtd, startaddr, length, &ul_retlen, databuf);
	if (0 != ret) {
		LOGE("spiflash_read_proc read error,lret[%u],ul_retlen[%u]\n", ret, ul_retlen);
	}
	
	LOGD("flash_read ok  startaddr = 0x%x\n",startaddr);

	return ret;
}


